using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.Linq;


using Soussous.Business;
using Soussous.DAO;
using Soussous.DAO.Connection;

namespace Soussous.DAO.Impl
{
    class UserDAO : AbstractDAO<User>
    {
        private static UserDAO INSTANCE = new UserDAO();

        public static UserDAO getInstance()
        {
            return INSTANCE;
        }

        private UserDAO()
        {
        }

        public Table<User> getTable()
        {
            return UserDAO.getInstance().getAll();
        }

        public List<User> getAllUser()
        {
            var userList = from e in getTable()
                           select e;

            return userList.ToList();
        }

        public bool searchMailUser(string email)
        {
            
            var userList = (from e in getTable()
                            where e.Email == email
                            select e).Count();


            return userList > 0;
        }

        public User searchMailUser1(string mail) {
            
            var userList = from e in getTable()
                            where e.Email == mail
                            select e;


            return userList.Count() > 0 ? userList.First() : null;
        }

        public User authenticate(string email, string pass)
        {


            var userList = from e in getTable()
                           where e.Password == pass && e.Email == email
                           select e;

            return userList.Count() > 0 ? userList.First() : null;
        }

        public User searchUserById(int id)
        {
            var userList = from e in getTable()
                           where e.Id == id
                           select e;


            return userList.Count() > 0 ? userList.First() : null;
        }

        public void updateUserById(int id, User user)
        {

            Table<User> users = getTable();
            var update = users.First(e => e.Id == id);
            update.Firstname = user.Firstname;
            update.Email = user.Email;
            update.Lastname = user.Lastname;
            update.Password = user.Password;
            users.Context.SubmitChanges();
        }

        public void deleteUserById(int id)
        {
            Table<User> users = getTable();
            var result = (from user in users
                          where user.Id == id
                          select user);
            users.DeleteOnSubmit(result.Single());
            users.Context.SubmitChanges();

        }
    }
}